//
//  FMDBManger.m
//  LittleSummary
//
//  Created by 郝旭珊 on 2018/2/3.
//  Copyright © 2018年 郝旭珊. All rights reserved.
//

#import "FMDBManger.h"

@interface FMDBManager()
@end


@implementation FMDBManager

#pragma mark - 初始化
+ (instancetype) sharedManager{
    static FMDBManager *instance;
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init] ;
    });
    return instance;
}


+ (id) allocWithZone:(struct _NSZone *)zone{
    return [FMDBManager sharedManager];
}


- (id) copyWithZone:(struct _NSZone *)zone{
    return [FMDBManager sharedManager];
}


- (instancetype)init{
    if (self = [super init]){
        NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).lastObject;
        NSString *dataBasePath = [documentPath stringByAppendingPathComponent:@"goods.db"];
        NSLog(@"数据库路径: %@",dataBasePath);

        // 1. 打开数据库队列
        // 如果数据库不存在，会建立数据库，然后，再创建队列并且打开数据库
        // 如果数据库存在，会直接创建队列并且打开数据库
        self.queue = [[FMDatabaseQueue alloc]initWithPath:dataBasePath];

        //2.创建数据表
        [self creatTable];

    }
    return self;
}


- (void)creatTable{
    //1.准备出创建表的 sql 语句
    NSString *path = [[NSBundle mainBundle]pathForResource:@"db.sql" ofType:nil];
    NSString *sql = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    //2.执行 sql 创表
    [self.queue inDatabase:^(FMDatabase *db) {
        // 创建数据表的时候，最好选择 executeStatements，可以执行多个 SQL
        // 保证能够一次性创建所有的数据表！
        if ([db executeStatements:sql]){ 
            NSLog(@"创表成功");
        }else{
            NSLog(@"创表失败");
        }
    }];
}

- (void)select:(NSString *)sql finished:(finishedOfSelect)finishedSelect{
//    NSString *sql = @"SELECT id, name, price, description, number FROM T_Goods;";
    NSArray *resultArray = [[FMDBManager sharedManager] executeSelectSql:sql];
    NSLog(@"%@",resultArray);
    finishedSelect(resultArray);
}

//- (void)select2:(NSString *)sql finishedOfSelect2:(void(^)(NSArray *results))finishedSelect2{
//    //    NSString *sql = @"SELECT id, name, price, description, number FROM T_Goods;";
//    NSArray *resultArray = [[FMDBManager sharedManager] executeSelectSql:sql];
//    NSLog(@"%@",resultArray);
//    finishedSelect2(resultArray);
//}


- (void)update:(NSString *)sql dict:(NSDictionary *)dict{
    [self.queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql withParameterDictionary:dict]){
            NSLog(@"修改了%d行",db.changes);
        }else{
            NSLog(@"修改失败");
        }
    }];
}



- (void)deleteSqlWithId:(NSNumber *)Id{
    NSString *sql = @"DELETE FROM T_Goods WHERE id = :id;";
    [self.queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql,Id]){
            NSLog(@"删除了%d行",db.changes);
        }else{
            NSLog(@"删除失败");
        }
    }];
}




- (BOOL)insert:(NSString *)sql dict:(NSDictionary *)dict{
    BOOL __block isSuccess;
    [self.queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql withParameterDictionary:dict]){
            isSuccess = YES;
        }else{
            isSuccess = NO;
        }
    }];
    return isSuccess;
}




- (NSArray *_Nullable)executeSelectSql:(NSString *)sql{

    NSMutableArray __block *result = [NSMutableArray array];

    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:sql];
        if (!rs){
            NSLog(@"没有查询到结果");
            return;
        }


        // while ([rs next]) FMDB 中的方法
        while ([rs next]) {
            //列数(属性数)
            NSInteger colCount = [rs columnCount];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];

            //遍历某一行的全部列, 得到一个完整的对象字典
            for (int i=0;i<colCount;i++){
                //第 i 列的属性名
                NSString *name = [rs columnNameForIndex:i];
                //第 i 列的属性值
                id obj = [rs objectForColumnIndex:i];
                [dict setValue:obj forKey:name];
            }
            [result addObject:dict];
        }

    }];

    return [result copy];
}

@end
